#!/usr/bin/env python 3
# -*- coding: utf-8 -*-

#
# Copyright (c) 2022 PanXu, Inc. All Rights Reserved
#
"""
brief

Authors: PanXu
Date:    2022/10/17 14:11:00
"""
import math

import pygame
from math import pi
import random
import time


def draw_text(surf, clear_text_rect, text, size, x, y):
    """显示文字的函数"""
    font_obj = pygame.font.SysFont("songti", size)

    text_surf = font_obj.render(text, True, (255, 255, 255))  # True为开启平滑字体显示(anti_aliasing)
    text_rect = text_surf.get_rect()
    text_rect.midtop = (x, y)

    if clear_text_rect is not None:
        surf.fill((0, 0, 0), clear_text_rect)

    surf.blit(text_surf, text_rect)

    return text_rect

pygame.init()

size = (600, 600)

screen = pygame.display.set_mode(size)
pygame.display.set_caption("蒙特卡洛求圆周率")
done = False

# 设置圆的半径
r = 100

# 设置圆心
center_x = size[0] / 2
center_y = size[1] / 2

rect_num = 0
circle_num = 0

step_num = 0

begin = time.time()

step_info_clear_rect = None
used_time_info_clear_rect = None

while not done:
    step_num += 1

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True  # 若检测到关闭窗口，则将done置为True

    # 绘制正方形
    pygame.draw.rect(screen, (0, 0, 255), [center_x - r, center_y - r, 2 * r, 2 * r], 1)

    # 绘制圆
    pygame.draw.arc(screen, (255, 0, 0), [center_x - r, center_y - r, 2 * r, 2 * r], 0, 2 * math.pi, 1)

    x = random.uniform(center_x - r, center_x + r)
    y = random.uniform(center_y - r, center_y + r)

    rect_num += 1

    if (x - center_x) * (x - center_x) + (y - center_y)*(y - center_y) <= r * r:
        circle_num += 1
        pygame.draw.circle(screen, (255, 0, 0), [x, y], 1)
    else:
        pygame.draw.circle(screen, (0, 0, 255), [x, y], 1)

    step_info = ""
    used_time = time.time() - begin
    used_time_info = f"耗时: {used_time:.2f} 秒"

    if rect_num > 0:
        pi = 4 * (circle_num/rect_num)
        step_info = f"迭代{step_num}步 圆周率:{pi}"
        show_info = f"{step_info} {used_time_info}"
        print(step_info)

    if step_num % 50 == 0:
        step_info_clear_rect = draw_text(screen, step_info_clear_rect, step_info, 24, 300, 50)
        used_time_info_clear_rect = draw_text(screen, used_time_info_clear_rect, used_time_info, 24, 300, 100)
    pygame.display.flip()

pygame.quit()
